﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace OrBitDataModule.Extensions
{
    public static class HttpExtend
    {
        #region Http服务扩展方法
        /// <summary>
        /// 解析POST表单数据
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static NameValueCollection ParseForm(this HttpListenerRequest @this, Encoding defaultEncoding)
        {
            NameValueCollection formFields = new NameValueCollection();
            // 处理 POST 请求
            if (@this.HttpMethod == "POST")
            {
                string responseString = string.Empty;
                // 如果是表单数据(content-type: multipart/form-data)，则读取数据
                if (@this.ContentType.StartsWith("multipart/form-data"))
                {
                    using (StreamReader reader = new StreamReader(@this.InputStream, defaultEncoding))
                    {
                        var boundary = Regex.Match(@this.ContentType, @"boundary=(?<token>.*)").Groups["token"].Value;
                        string requestBody = reader.ReadToEnd();
                        var parts = requestBody.Split(new[] { $"--{boundary}" }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (var part in parts)
                        {
                            if (string.IsNullOrWhiteSpace(part) || part == "--")
                                continue;

                            var endOfHeaders = part.IndexOf("\r\n\r\n", StringComparison.Ordinal);
                            if (endOfHeaders >= 0)
                            {
                                var headers = part.Substring(0, endOfHeaders);
                                var content = part.Substring(endOfHeaders + 4);
                                var nameMatch = Regex.Match(headers, @"name=""(?<name>.+?)""");
                                if (nameMatch.Success)
                                {
                                    var name = nameMatch.Groups["name"].Value;
                                    content = content.Trim('\r', '\n');
                                    formFields.Add(name, content);
                                }
                            }
                        }
                        foreach (var fieldKey in formFields.AllKeys)
                        {
                            responseString += $"{fieldKey}: {formFields[fieldKey]}\r\n";
                        }
                    }
                }

                else if (@this.ContentType == "application/x-www-form-urlencoded")
                {
                    using (StreamReader reader = new StreamReader(@this.InputStream, @this.ContentEncoding))
                    {
                        string formData = reader.ReadToEnd();
                        // 此时formData是一个Key=Value&Key2=Value2格式的字符串
                        // 解析表单数据
                        formFields = System.Web.HttpUtility.ParseQueryString(formData);
                    }
                }
            }
            return formFields;
        }
        #endregion
    }
}
